package com.example.zrq1010110087.graceplayer.data;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;
import android.widget.Toast;

import com.example.zrq1010110087.graceplayer.R;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by zrq1010110087 on 2017/10/16.
 *  This is a MediaPlayerUser which invoke the method of MediaPlayer to control music
 *
 */

public class MediaPlayerUser {
    private  MediaPlayer mediaPlayer=new MediaPlayer();
    private ArrayList<Music> arrayList;
    private Context context;
    private  volatile int number=0;

    //初始化音乐列表类
    public MediaPlayerUser(ArrayList<Music> arrayList,Context context){

        this.arrayList=arrayList;
        this.context=context;
    }


    //设置number
    public void setMusicNumber(int number){

        this.number=number;

    }
    //得到number
    public int getMusicNumber(){

        return number;

    }

     //加载音乐
    public void load()  {
      try {

             //进入游离态
              mediaPlayer.reset();
              //进入初始态
              mediaPlayer.setDataSource(arrayList.get(number).getmusicPath());
              //进入准备态
              mediaPlayer.prepare();


      }catch (Exception e){

          e.printStackTrace();
      }
    }

    //播放音乐
    public void play() {

        //若音乐处于播放当中,则停止播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {

            mediaPlayer.stop();

        }
                load();
                mediaPlayer.start();


            }

      //暂停音乐
        public void pause () {

            //若处于运行态
            if (mediaPlayer.isPlaying()) {

                mediaPlayer.pause();
            }

        }

        //停止音乐
        public void stop () {

            mediaPlayer.stop();
        }

        //恢复（即继续）音乐播放
        public void resume () {

            mediaPlayer.start();
        }

        //重新播放音乐
        public void replay () {

            mediaPlayer.start();
        }

        //播放上一首
       public void moveToPrevious(Context context){

           //若到第一首,提醒用户
           if(number==0){

               Toast.makeText(context,context.getString(R.string.musiclist_top),Toast.LENGTH_SHORT).show();
           }else{
               --number;
               play();

           }


       }
       //播放下一首
        public void moveToNext(Context context){

            //若到最后一首,提醒用户
            if(number==arrayList.size()-1){

                Toast.makeText(context,context.getString(R.string.musiclist_bottom),Toast.LENGTH_SHORT).show();
            }else{
                ++number;
                play();

            }

        }
        //判断播放状态
        public  boolean Playing(){

            return mediaPlayer.isPlaying();
        }




    }
